package com.yc.http.d0704;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {

    private InputStream inputStream;
    // 地址
    private String requestURI;
    // 方法, 类型
    private String method;
    // 协议
    private String protocol;
    // 头域参数集合
    private Map<String, String> headers = new HashMap<>();

    private Cookie[] cookies;

    public HttpServletRequest(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;
        try {
            // 读取请求报文
            byte[] buffer = new byte[1024 * 10];
            int count = inputStream.read(buffer);
            String requestStr = new String(buffer, 0, count);
            System.out.println(requestStr);
            // 获取资源地址
            String[] lines = requestStr.split("\r\n");
            String[] items = lines[0].split("\\s");
            method = items[0];
            requestURI = items[1];
            protocol = items[2];

            for (int i = 1; i < lines.length; i++) {
                if (lines[i].isEmpty()) {
                    break;
                }
                items = lines[i].split(":\\s*");
                if (items.length > 1) {
                    headers.put(items[0], items[1]);
                }
            }

            String cookieStr = headers.get("Cookie");
            if (cookieStr != null) {
                items = cookieStr.split(";\\s*");
                if (items.length > 0) {
                    ArrayList<Cookie> list = new ArrayList<>();
                    for (int i = 0; i < items.length; i++) {
                        String[] is = items[i].split("=");
                        list.add(new Cookie(is[0], is[1]));
                    }
                    this.cookies = list.toArray(new Cookie[list.size()]);
                }
            }
            System.out.println("=========" + this);

        } catch (IOException e) {
            throw e;
        }
    }

    public String getMethod() {
        return method;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getParameter(String name) {
        return null;
    }

    public String getHeader(String name) {
        return headers.get(name);
    }

    // 获取请求中的cookie数据
    public Cookie[] getCookies() {
        return cookies;
    }

    public String getRequestURI() {
        return requestURI;
    }

    // alt + insert  代码提示
    @Override
    public String toString() {
        return "HttpServletRequest{" +
                "inputStream=" + inputStream +
                ", requestURI='" + requestURI + '\'' +
                ", method='" + method + '\'' +
                ", protocol='" + protocol + '\'' +
                ", headers=" + headers +
                '}';
    }


}
